<template>
  <div>
    <!-- 查询表单 -->
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.paperName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入试卷名称查询"></el-input>
      <el-input v-model="data.courseName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入课程名称查询"></el-input>
      <el-input v-model="data.examStatus" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入阅卷状态查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <!-- 表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData">
        <el-table-column prop="paperName" label="试卷名称" show-overflow-tooltip/>
        <el-table-column prop="courseName" label="课程名称" show-overflow-tooltip/>
        <el-table-column prop="teacherName" label="授课教师" show-overflow-tooltip v-if="data.user.role === 'ADMIN'"/>
        <el-table-column prop="userName" label="学生姓名" show-overflow-tooltip/>
        <el-table-column prop="examStatus" label="试卷状态" show-overflow-tooltip>
          <template v-slot="scope">
            <el-tag v-if="scope.row.examStatus === 1" type="success">已阅卷</el-tag>
            <el-tag v-if="scope.row.examStatus === 0" type="danger">未阅卷</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" show-overflow-tooltip/>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button :disabled="scope.row.examStatus === 1" type="primary" @click="handleEdit(scope.row)">阅卷</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <!-- 阅卷对话框 -->
    <el-dialog title="试卷信息" v-model="data.formVisible" width="85%" destroy-on-close>
      <div v-if="data.testPaperData">
        <div class="test-paper-header">
          <div class="paper-name">{{ data.testPaperData.paperName }}</div>
          <div class="course-teacher-info">
            <span>课程名称：{{ data.testPaperData.courseName }}</span>
            <span>授课教师：{{ data.testPaperData.teacherName }}</span>
          </div>
        </div>
        <div class="questions-container">
          <div v-for="question in data.testPaperData.questionRespDTOs" :key="question.id" class="question-item">
            <div class="question-header">
              {{ question.questionStem }}（{{ question.score }} 分）
            </div>

            <!-- 图片展示 -->
            <div v-if="question.questionImg && question.questionImg.length > 0" class="question-images">
              <el-image
                  v-for="(imgUrl, imgIndex) in question.questionImg"
                  :key="imgIndex"
                  :src="imgUrl"
                  fit="contain"
                  style="width: 150px; height: 150px; margin-right: 10px; cursor: pointer;"
                  @click="handleImageClick(imgUrl)"
              />
            </div>

            <div class="user-answer">
              <span>用户答案：</span>
              <span>{{ formatUserAnswer(question.newAnswer) }}</span>
            </div>
            <div class="answer-results">
              <span>标准答案：{{ formatUserAnswer(question.answer) }}</span>
            </div>
            <div v-if="question.typeId === 1 || question.typeId === 2" class="options">
              <div v-for="(option, index) in question.options" :key="index" class="option">
                <el-radio v-if="question.typeId === 1" v-model="question.newAnswer" :label="option.optionLabel" disabled>
                  {{ option.optionLabel }}. {{ option.optionValue }}
                </el-radio>
                <el-checkbox v-if="question.typeId === 2" v-model="question.newAnswerArray" :label="option.optionLabel" disabled>
                  {{ option.optionLabel }}. {{ option.optionValue }}
                </el-checkbox>
              </div>
            </div>
            <div class="score-input">
              <span>得分：</span>
              <el-input-number v-model="question.newScore" :min="0" :max="question.score" />
            </div>
            <!-- AI评语部分 -->
            <div v-if="question.aiRemark" class="ai-remark">
              <strong>AI评语：</strong>{{ question.aiRemark }}
            </div>
          </div>
        </div>
        <div class="total-score">
          <span>总分：<strong>{{ totalScore }}</strong></span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="update">提 交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-image-viewer
        v-if="data.imageViewerVisible"
        :url-list="[data.currentImageUrl]"
        @close="data.imageViewerVisible = false"
    />
  </div>
</template>

<script setup>
import { reactive, computed } from "vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

const data = reactive({
  user: JSON.parse(localStorage.getItem("user") || "{}"),
  formVisible: false,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  paperName: null,
  courseName: null,
  examStatus: null,
  scoreId: null,
  testPaperData: {},
  answerData: [],
  imageViewerVisible: false,
  currentImageUrl: ''
});

// 计算总分
const totalScore = computed(() => {
  return data.testPaperData.questionRespDTOs.reduce((sum, question) => sum + (question.newScore || 0), 0);
});

// 加载试卷列表
const load = () => {
  request.get("/score/selectPage", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      paperName: data.paperName,
      courseName: data.courseName,
      examStatus: data.examStatus
    }
  }).then(res => {
    if (res.code === "200") {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 打开阅卷对话框，加载对应试卷和答案信息
const handleEdit = (row) => {
  // 深拷贝当前行数据，防止直接修改列表数据
  data.form = JSON.parse(JSON.stringify(row));
  request.get(`/score/selectById/${row.id}`).then((res) => {
    if (res.code === "200") {
      data.scoreId = res.data.id;
      data.testPaperData = res.data.examPaperMsgRespDTO;
      // 解析remark并附加到对应的问题上
      const remarks = res.data.remark?.split("\n") || [];
      const remarkScores = {};
      remarks.forEach(remark => {
        const match = remark.match(/第(\d+)题: (.*) \[得分: (\d+)\]/);
        if (match) {
          const questionIndex = parseInt(match[1]) - 1;
          if (data.testPaperData.questionRespDTOs[questionIndex]) {
            data.testPaperData.questionRespDTOs[questionIndex].aiRemark = remark;
            remarkScores[data.testPaperData.questionRespDTOs[questionIndex].id] = parseInt(match[3]);
          }
        }
      });

      // 处理题目数据，添加用户答案和结果
      res.data.answerData.forEach((answerData) => {
        const question = data.testPaperData.questionRespDTOs.find((q) => q.id === answerData.questionId);
        if (question) {
          // 处理多选题的用户答案
          if (question.typeId === 2) {
            question.newAnswerArray = answerData.newAnswer.split(',').map(item => item.trim());
            question.newAnswer = question.newAnswerArray.join(',');
          } else {
            question.newAnswer = answerData.newAnswer;
          }

          // 初始化新得分为原有得分或AI评分
          question.newScore = remarkScores[question.id] !== undefined ? remarkScores[question.id] : calculateScore(question);
        }
      });
      data.formVisible = true;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 更新阅卷数据
const update = () => {
  // 构建新的 answerData 数组
  const newAnswerData = data.testPaperData.questionRespDTOs.map(question => ({
    questionId: question.id,
    score: question.newScore || 0
  }));

  // 更新表单数据
  data.form.answerData = newAnswerData;
  data.form.examStatus = 1; // 设置试卷状态为“已阅卷”
  data.form.totalScore = totalScore.value; // 添加总分字段
  data.form.score = totalScore.value;
  request.put("/score/update", data.form).then(res => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const reset = () => {
  data.paperName = null;
  data.courseName = null;
  data.examStatus = null;
  load();
};

// 定义 formatUserAnswer 函数
const formatUserAnswer = (answer) => {
  if (Array.isArray(answer)) {
    return answer.join(', ');
  }
  return answer;
};

// 根据题目类型计算得分
const calculateScore = (question) => {
  if (question.typeId === 1) { // 单选题
    return question.newAnswer === question.answer ? question.score : 0;
  } else if (question.typeId === 2) { // 多选题
    const userAnswers = new Set(question.newAnswerArray);
    const correctAnswers = new Set(question.answer.split(',').map(item => item.trim()));
    const intersectionSize = [...userAnswers].filter(value => correctAnswers.has(value)).length;
    if (intersectionSize === correctAnswers.size && intersectionSize === userAnswers.size) {
      return question.score;
    } else if (intersectionSize > 0) {
      return Math.floor((intersectionSize / correctAnswers.size) * question.score);
    } else {
      return 0;
    }
  } else if (question.typeId === 4 || question.typeId === 5) { // 填空题和简答题
    return question.newAnswer === question.answer ? question.score : 0;
  }
  return 0;
};

// 处理图片点击事件
const handleImageClick = (imgUrl) => {
  data.currentImageUrl = imgUrl;
  data.imageViewerVisible = true;
};

load();
</script>

<style scoped>
.card {
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  background-color: white;
  margin-bottom: 10px;
}

.test-paper-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.paper-name {
  font-size: 20px;
  font-weight: bold;
}

.course-teacher-info span {
  margin-right: 20px;
}

.questions-container {
  margin-bottom: 20px;
}

.question-item {
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
}

.question-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.user-answer, .answer-results {
  margin-bottom: 10px;
}

.options {
  margin-bottom: 10px;
}

.option {
  margin-bottom: 5px;
}

.score-input {
  margin-top: 10px;
}

.total-score {
  text-align: right;
  font-size: 18px;
  font-weight: bold;
}

.ai-remark {
  margin-top: 15px;
  color: #34495e;
  font-size: 16px;
  line-height: 1.5;
}

.question-images {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>



